<template>
  <div>
    <el-dialog v-model="dialogFormVisible" title="编辑用户">
      <el-form :model="form">
        <el-form-item label="用户账号" label-width="140px">
          <el-input v-model="form.username" autocomplete="off" />
        </el-form-item>
        <el-form-item label="用户密码" label-width="140px">
          <el-button type="primary" @click="RestPassword">重置密码</el-button>
        </el-form-item>

        <el-form-item label="状态" label-width="140px">
          <el-select-v2
            v-model="form.isEnable"
            :options="isEnableList"
            placeholder="用户状态"
          />
        </el-form-item>

        <el-form-item label="性别" label-width="140px">
          <el-select-v2
            v-model="form.sex"
            placeholder="请选择用户性别"
            :options="SexList"
          />
        </el-form-item>

        <el-form-item label="余额" label-width="140px">
          <el-input
            type="number"
            v-model="form.balance"
            placeholder="请输入余额"
          ></el-input>
        </el-form-item>

        <el-form-item label="昵称" label-width="140px">
          <el-input v-model="form.account" placeholder="请输入昵称"></el-input>
        </el-form-item>
        <el-form-item label="email" label-width="140px">
          <el-input v-model="form.email" placeholder="请输入电子邮箱"></el-input>
        </el-form-item>

        <el-form-item label="微信" label-width="140px">
          <el-input v-model="form.wxNum" placeholder="请输入微信"></el-input>
        </el-form-item>
        <el-form-item label="QQ" label-width="140px">
          <el-input v-model="form.qqNum" placeholder="请输入qq"></el-input>
        </el-form-item>
        <el-form-item label="address" label-width="140px">
          <el-input v-model="form.address" placeholder="请输入家庭住址"></el-input>
        </el-form-item>
        <el-form-item label="角色" label-width="140px">
          <el-select-v2
            :options="levelList"
            v-model="form.role"
            placeholder="请选择用户权限"
          />
        </el-form-item>

        <el-form-item label="图片" label-width="140px">
          <el-upload
            v-model:file-list="form.img"
            action="/api/upload/img"
            :headers="tokenBody"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="hanleSuccess"
            limit="1"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
        </el-form-item>
      </el-form>

      <el-dialog v-model="photoShowFlag">
        <img :src="dialogImageUrl" alt="Preview Image" />
      </el-dialog>

      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="Edit"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-dialog title="新增用户" v-model="ShopDialogFormVisible">
      <el-form :model="insert">
        <el-form-item label="登录账号" label-width="140px">
          <el-input v-model="insert.username" placeholder="请输入登录账号"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" label-width="140px">
          <el-input v-model="insert.password" placeholder="请输入用户密码" />
        </el-form-item>
        <el-form-item label="用户昵称" label-width="140px">
          <el-input v-model="insert.account" placeholder="请输入用户昵称" />
        </el-form-item>
        <el-form-item label="email" label-width="140px">
          <el-input v-model="insert.email" type="email" placeholder="请输入用户email" />
        </el-form-item>
        <el-form-item label="性别" label-width="140px">
          <el-select-v2
            :options="SexList"
            v-model="insert.sex"
            placeholder="请选择用户性别"
          />
        </el-form-item>
        <el-form-item label="用户权限" label-width="140px">
          <el-select-v2
            :options="levelList"
            v-model="insert.role"
            placeholder="请选择用户权限"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="ShopDialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="insertAll"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>

    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/manager/index' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item><a href="/manager/user">用户信息</a></el-breadcrumb-item>
    </el-breadcrumb>
    <div class="header">
      <div style="width: 200px">
        <el-input v-model="input" placeholder="请输入搜索内容" />
      </div>
      <el-button type="primary" @click="search" style="margin-left: 10px">搜索</el-button>
      <el-button type="primary" @click="Research">重置</el-button>
    </div>
    <div class="insert">
      <el-button type="info" size="large" @click="ChooseIF" style="margin-right: 50px"
        >新增用户</el-button
      >
    </div>
    <el-table :data="tableData" style="width: 100%">
      <el-table-column label="账号" prop="username" />

      <el-table-column label="昵称" prop="account" />

      <el-table-column label="性别" prop="sex"> </el-table-column>
      <el-table-column label="图片" width="120px">
        <template #default="scope">
          <div class="demo-image__preview">
            <el-image
              style="width: 100px; height: 100px"
              :src="scope.row.img"
              :zoom-rate="1.2"
              :max-scale="7"
              :min-scale="0.2"
              :initial-index="4"
              fit="cover"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="余额" prop="balance"> </el-table-column>
      <el-table-column label="注册时间" prop="inputTime" width="200px" />
      <el-table-column label="最近更新时间" prop="updateTime" width="200px" />

      <el-table-column label="Operations">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)"
            >编辑</el-button
          >
          <el-button
            size="small"
            type="danger"
            @click="handleDelete(scope.$index, scope.row)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      v-model:current-page="pageSize"
      v-model:page-size="pageItem"
      :page-sizes="[20, 30, 50, 100]"
      :small="small"
      :disabled="disabled"
      :background="background"
      layout="total, sizes, prev, pager, next, jumper"
      :total="ItemTotal"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </div>
</template>

<script lang="ts" setup>
import axios from "axios";
import { ref, reactive } from "vue";
import { Timer, Message } from "@element-plus/icons-vue";
import { el } from "element-plus/es/locale";
import { ElMessage, ElMessageBox } from "element-plus";
import { Delete, Download, Plus, ZoomIn } from "@element-plus/icons-vue";
import type { UploadFile } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";

const token = ref(localStorage.getItem("admin_token"));

const tokenBody = {
  token: token.value,
};

const SexList = [
  {
    label: "男",
    value: "男",
  },
  {
    label: "女",
    value: "女",
  },
  {
    label: "保密",
    value: "保密",
  },
];
const levelList = [
  {
    label: "普通用户",
    value: "user",
  },
  {
    label: "管理员",
    value: "admin",
  },
];

const optionList = ref([
  {
    label: "正常",
    value: "1",
  },
  {
    label: "禁用",
    value: "0",
  },
]);

const isEnableList = [
  {
    label: "正常",
    value: "1",
  },
  {
    label: "禁用",
    value: "0",
  },
];

const ShopDialogFormVisible = ref(false);

const Edit = () => {
  console.log(form);
  console.log(form.img);
  const req = {
    userId: form.userId,
    username: form.username,
    password: form.password,
    sex: form.sex,
    account: form.account,
    isEnable: form.isEnable,
    balance: form.balance,
    img: form.relImg,
    email: form.email,
    wxNum: form.wxNum,
    qqNum: form.qqNum,
    role: form.role,
    address: form.address,
  };

  axios
    .post("/api/manager/user/update", req, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      console.log(res);
      if (res.data.success) {
        ElMessage({
          message: "更新成功",
          type: "success",
        });
      } else {
        ElMessage({
          message: res.data.message,
          type: "error",
        });
      }
      search();
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    dialogFormVisible.value = false;
  }, 200);
};

const RestPassword = () => {
  axios
    .get("/api/manager/user/Resetpassword/" + form.userId, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      if (res.data.success) {
        ElMessage({
          message: "重置成功,初识密码为123456",
          type: "success",
        });
      } else {
        ElMessage({
          message: res.data.message,
          type: "error",
        });
      }
      search();
    })
    .catch((err) => {});
};
// const fileList = ref<UploadUserFile[]>([]);

const dialogFormVisible = ref(false);
const photoShowFlag = ref(false);
const dialogImageUrl = ref("");

const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};

const hanleSuccess: UploadProps["onSuccess"] = (res) => {
  // console.log(res);
  // form.img.push({
  //   name: res.message,
  //   url: res.message,
  // });
  // console.log(form.img);

  form.img = <UploadUserFile[]>[];
  form.img.push({
    name: res.message,
    url: res.message,
  });
  form.relImg = res.message;
  // console.log(JSON.stringify(form.img));
};

const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  photoShowFlag.value = true;
};

interface User {
  userId: string;
  username: string;
  password: string;
  sex: string;
  role: string;
  isEnable: string;
  demo: string;
  qqNum: string;
  wxNum: string;
  email: string;
  account: string;
  inputTime: Date;
  updateTime: Date;
  state: string;
  balance: number;
  img: string;
  address: string;
  bornDate: Date;
}

const insert = reactive({
  username: "",
  password: "",
  sex: "保密",
  account: "",
  role: "user",
  email: "",
});

const insertAll = () => {
  const req = {
    username: insert.username,
    password: insert.password,
    sex: insert.sex,
    account: insert.account,
    role: insert.role,
    email: insert.email,
  };
  axios
    .post("/api/manager/user/insert", req, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      // console.log(res);
      if (res.data.success) {
        ElMessage({
          type: "success",
          message: "新建成功",
        });
      } else {
        ElMessage({
          type: "error",
          message: res.data.message,
        });
      }
    })
    .catch((err) => {
      console.log(err);
    });
  setTimeout(() => {
    insert.username = "";
    insert.password = "";
    insert.sex = "保密";
    insert.account = "";
    insert.role = "user";
    insert.email = "";
    ShopDialogFormVisible.value = false;
    search();
  }, 200);
};

const form = reactive({
  userId: "",
  username: "",
  password: "",
  sex: "",
  account: "",
  inputTime: new Date(),
  updateTime: new Date(),
  balance: 0,
  img: <UploadUserFile[]>[],
  relImg: "", //真实图像
  email: "",
  wxNum: "",
  qqNum: "",
  role: "",
  address: "",
  isEnable: "",
});
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  search();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  search();
};

const handleEdit = (index: number, row: User) => {
  form.account = "";
  form.balance = 0;
  form.inputTime = new Date();
  form.updateTime = new Date();
  form.password = "";
  form.sex = "";
  form.userId = row.userId;
  form.img = <UploadUserFile[]>[];
  form.relImg = "";
  form.email = "";
  form.wxNum = "";
  form.qqNum = "";
  form.role = "";
  form.address = "";
  form.isEnable = "1";

  axios
    .get("/api/manager/user/get/" + row.userId, {
      headers: {
        token: token.value,
      },
    })
    .then((res) => {
      console.log(res);
      form.account = res.data.message.account;
      form.username = res.data.message.username;
      form.balance = res.data.message.balance;
      form.inputTime = res.data.message.inputTime;
      form.updateTime = res.data.message.updateTime;
      form.password = res.data.message.password;
      form.sex = res.data.message.sex;
      form.userId = res.data.message.userId;
      if (res.data.message.img) {
        form.img.push({
          name: res.data.message.img,
          url: res.data.message.img,
        });
        form.relImg = res.data.message.img;
        console.log("form.img :", form.img);
      }
      if (res.data.message.email) {
        form.email = res.data.message.email;
      }
      if (res.data.message.wxNum) {
        form.wxNum = res.data.message.wxNum;
      }
      if (res.data.message.qqNum) {
        form.qqNum = res.data.message.qqNum;
      }
      if (res.data.message.role) {
        form.role = res.data.message.role;
      }
      if (res.data.message.address) {
        form.address = res.data.message.address;
      }
      form.isEnable = res.data.message.isEnable;

      search();
    })
    .catch((err) => {
      console.log(err);
    });
  console.log(JSON.stringify(form));

  setTimeout(() => {
    dialogFormVisible.value = true;
    console.log(index, row);
  }, 300);
};

const handleDelete = (index: number, row: User) => {
  console.log(index, row);
  console.log(row);

  ElMessageBox.confirm("是否删除该用户" + row.username, "警告", {
    confirmButtonText: "确认删除",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      axios
        .get("/api/manager/user/del/" + row.userId, {
          headers: {
            token: token.value,
          },
        })
        .then((res) => {
          console.log(res);
          if (res.data.success) {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          } else {
            ElMessage({
              type: "error",
              message: res.data.message,
            });
          }
          search();
        })
        .catch((err) => {
          console.log(err);
        });
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const tableData = ref([]);

const input = ref("");
const pageSize = ref(1);
const pageItem = ref(20);
const PageTotal = ref(0);
const ItemTotal = ref(0);
const search = () => {
  axios
    .get(
      "/api/manager/user/select/" +
        pageSize.value +
        "/" +
        pageItem.value +
        "?name=" +
        input.value,
      {
        headers: {
          token: token.value,
        },
      }
    )
    .then((res) => {
      console.log(res);
      const msg = res.data.message.list;
      console.log(msg);

      tableData.value = msg;
      console.log(tableData.value);
      PageTotal.value = res.data.message.pages;
      ItemTotal.value = res.data.message.total;
    })
    .catch((err) => {
      console.log(err);
    });
};

const Research = () => {
  pageSize.value = 1;
  pageItem.value = 20;
  input.value = "";
  search();
};
const ChooseIF = () => {
  ShopDialogFormVisible.value = true;
};

search();
</script>

<style lang="scss" scoped>
.header {
  height: 50px;
  display: flex;
  justify-content: flex-end;
  align-items: center;
}
.insert {
  display: flex;
  justify-content: flex-end;
  width: 100%;
}
</style>
